package cn.xawl.interview.thread;

import java.util.concurrent.*;

/**
 * @author lh
 * @date 2020/08/26 18:07:41
 **/
public class BlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {

        //链表阻塞队列大小默认是Integer.MAX_VALUE，因此尽量自己设置大小
//        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(3);

        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(1);
        blockingQueue.offer(1, 2, TimeUnit.SECONDS);
        System.out.println(blockingQueue.offer(1, 2, TimeUnit.SECONDS));


    }

    private static void syncQueue() throws InterruptedException {
        //同步队列：固定大小为1，即放入就要取出，否则抛异常、特殊值、阻塞
        BlockingQueue<Integer>  blockingQueue = new SynchronousQueue<>();

        blockingQueue.put(1);
        blockingQueue.put(12);
    }

    private static void blockingQueueMethods() throws InterruptedException {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

        //抛异常
        blockingQueue.add("a");
        blockingQueue.add("a");
        blockingQueue.add("a");

        blockingQueue.remove();

        System.out.println("==========");


        //特殊值
        blockingQueue.offer("a");
        blockingQueue.offer("a");
        blockingQueue.offer("a");

        blockingQueue.poll();
        System.out.println("==========");

        //阻塞
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        System.out.println("==========");

        blockingQueue.take();
        blockingQueue.put("d");
        //超时
        System.out.println("==========");

        blockingQueue.offer("a", 2, TimeUnit.SECONDS);
        blockingQueue.offer("a", 2, TimeUnit.SECONDS);
        blockingQueue.offer("a", 2, TimeUnit.SECONDS);

        blockingQueue.poll(2, TimeUnit.SECONDS);

    }

}
